//
//  OPRequesterManager.m
//  OnePiece
//
//  Created by wsy on 15/10/24.
//  Copyright © 2015年 wsy. All rights reserved.
//

#import "OPRequesterManager.h"

@implementation OPRequesterManager
- (void)requestWithType:(RequestType)type urlString:(NSString *)urlString parDic:(NSDictionary *)parDic finish:(RequestFinish)finish error:(RequestError)error
{
    // 拿到参数之后进行请求
    NSURL *url = [NSURL URLWithString:urlString];
    // 创建可变的URLRequest
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 如果请求方式是POST还需要设置参数和请求方式
    if (type == POST) {
        // 设置请求方式
        [request setHTTPMethod:@"POST"];
        if (parDic.count > 0) {
            // 设置请求参数的Body体
            [request setHTTPBody:[self parDicToDataWithDic:parDic]];
        }
    }
    [NSURLConnection sendAsynchronousRequest:request queue:([NSOperationQueue currentQueue]) completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            finish(data);
        }else{
            error(connectionError);
        }
    }];
}

- (NSData *)parDicToDataWithDic:(NSDictionary *)dic
{
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
    // 遍历字典得到每一个key = value型字符串
    for (NSString *key in dic) {
        NSString *str = [NSString stringWithFormat:@"%@=%@",key, dic[key]];
        [array addObject:str];
    }
    // 数组里所有key=value的字符串的拼接
    NSString *parStr = [array componentsJoinedByString:@"&"];
    return [parStr dataUsingEncoding:NSUTF8StringEncoding];
}

+ (void)requestWithType:(RequestType)type urlString:(NSString *)urlString parDic:(NSDictionary *)parDic finish:(RequestFinish)finish error:(RequestError)error
{
    OPRequesterManager *manager = [[OPRequesterManager alloc]init];
    [manager requestWithType:(type) urlString:(urlString) parDic:parDic finish:finish error:error];
}


@end
